<template>
  <div class="container">
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="分娩日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item label="种母耳号">
          <el-input v-model="searchForm.eweEarTag" placeholder="请输入种母耳号" clearable />
        </el-form-item>
        <el-form-item label="转入栋舍">
          <el-input v-model="searchForm.transferInPen" placeholder="请输入转入栋舍" clearable />
        </el-form-item>
        <el-form-item label="转出栋舍">
          <el-input v-model="searchForm.transferOutPen" placeholder="请输入转出栋舍" clearable />
        </el-form-item>
        <el-form-item label="窝号">
          <el-input v-model="searchForm.litterNumber" placeholder="请输入窝号" clearable />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="searchForm.responsiblePerson" placeholder="请输入负责人" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增按钮 -->
    <div style="margin-bottom: 16px;">
      <el-button type="primary" @click="goToAdd">新增</el-button>
    </div>
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        :max-height="600"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="eweEarTag" label="种母耳号" width="120" align="center" />
        <el-table-column prop="lambingDate" label="分娩日期" width="120" align="center">
          <template #default="scope">{{ formatDate(scope.row.lambingDate) }}</template>
        </el-table-column>
        <el-table-column prop="gestationDays" label="妊娠天数" width="100" align="center" />
        <el-table-column prop="lambingDifficulty" label="分娩难易程度" width="120" align="center" />
        <el-table-column prop="maternalInstinct" label="母性表现" width="100" align="center" />
        <el-table-column prop="lactation" label="泌乳情况" width="100" align="center" />
        <el-table-column prop="mastitis" label="乳房炎情况" width="100" align="center" />
        <el-table-column prop="totalLambCount" label="羔总羔数" width="100" align="center" />
        <el-table-column prop="totalLitterWeight" label="羔总重(kg)" width="120" align="center" />
        <el-table-column prop="liveLambCount" label="活羔总数" width="100" align="center" />
        <el-table-column prop="liveLambWeight" label="活羔总重(kg)" width="120" align="center" />
        <el-table-column prop="avgLiveLambWeight" label="活羔均重(kg)" width="120" align="center" />
        <el-table-column prop="deadLambCount" label="死羔总数" width="100" align="center" />
        <el-table-column prop="deadLambWeight" label="死羔总重(kg)" width="120" align="center" />
        <el-table-column prop="avgDeadLambWeight" label="死羔均重(kg)" width="120" align="center" />
        <el-table-column prop="fatLambBatch" label="肥羊批次" width="100" align="center" />
        <el-table-column prop="healthyLambCount" label="健羔数" width="100" align="center" />
        <el-table-column prop="weakLambCount" label="弱羔数" width="100" align="center" />
        <el-table-column prop="deformedLambCount" label="畸形数" width="100" align="center" />
        <el-table-column prop="stillbirthCount" label="死胎数" width="100" align="center" />
        <el-table-column prop="abnormalFetusCount" label="畸胎数" width="100" align="center" />
        <el-table-column prop="mummifiedFetusCount" label="木乃伊数" width="100" align="center" />
        <el-table-column prop="litterNumber" label="窝号" width="100" align="center" />
        <el-table-column prop="gender" label="性别" width="80" align="center" />
        <el-table-column prop="currentPen" label="当前栋舍" width="100" align="center" />
        <el-table-column prop="currentStall" label="当前栏位" width="100" align="center" />
        <el-table-column prop="transferInPen" label="转入栋舍" width="100" align="center" />
        <el-table-column prop="transferInStall" label="转入栏位" width="100" align="center" />
        <el-table-column prop="transferOutPen" label="转出栋舍" width="100" align="center" />
        <el-table-column prop="responsiblePerson" label="负责人" width="100" align="center" />
        <el-table-column prop="creator" label="创建人" width="100" align="center" />
        <el-table-column prop="createTime" label="创建时间" width="150" align="center">
          <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
        </el-table-column>
        <el-table-column prop="modifyTime" label="修改时间" width="150" align="center">
          <template #default="scope">{{ formatDate(scope.row.modifyTime) }}</template>
        </el-table-column>
        <el-table-column prop="documentNumber" label="单据号" width="120" align="center" />
        <el-table-column prop="status" label="状态" width="100" align="center" />
      </el-table>
    </div>
    <!-- 新增对话框 -->
    <el-dialog v-model="showAddDialog" title="新增种母分娩" width="600px">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="120px">
        <el-form-item label="种母耳号" prop="EweEarTag">
          <el-input v-model="addForm.EweEarTag" />
        </el-form-item>
        <el-form-item label="分娩日期" prop="LambingDate">
          <el-date-picker v-model="addForm.LambingDate" type="date" value-format="YYYY-MM-DD" style="width:100%" />
        </el-form-item>
        <el-form-item label="妊娠天数" prop="GestationDays">
          <el-input v-model.number="addForm.GestationDays" type="number" />
        </el-form-item>
        <el-form-item label="分娩难易程度" prop="LambingDifficulty">
          <el-input v-model="addForm.LambingDifficulty" />
        </el-form-item>
        <el-form-item label="母性表现" prop="MaternalInstinct">
          <el-input v-model="addForm.MaternalInstinct" />
        </el-form-item>
        <el-form-item label="泌乳情况" prop="Lactation">
          <el-input v-model="addForm.Lactation" />
        </el-form-item>
        <el-form-item label="乳房炎情况" prop="Mastitis">
          <el-input v-model="addForm.Mastitis" />
        </el-form-item>
        <el-form-item label="羔总羔数" prop="TotalLambCount">
          <el-input v-model.number="addForm.TotalLambCount" type="number" />
        </el-form-item>
        <el-form-item label="羔总重(kg)" prop="TotalLitterWeight">
          <el-input v-model.number="addForm.TotalLitterWeight" type="number" />
        </el-form-item>
        <el-form-item label="活羔总数" prop="LiveLambCount">
          <el-input v-model.number="addForm.LiveLambCount" type="number" />
        </el-form-item>
        <el-form-item label="活羔总重(kg)" prop="LiveLambWeight">
          <el-input v-model.number="addForm.LiveLambWeight" type="number" />
        </el-form-item>
        <el-form-item label="活羔均重(kg)" prop="AvgLiveLambWeight">
          <el-input v-model.number="addForm.AvgLiveLambWeight" type="number" />
        </el-form-item>
        <el-form-item label="死羔总数" prop="DeadLambCount">
          <el-input v-model.number="addForm.DeadLambCount" type="number" />
        </el-form-item>
        <el-form-item label="死羔总重(kg)" prop="DeadLambWeight">
          <el-input v-model.number="addForm.DeadLambWeight" type="number" />
        </el-form-item>
        <el-form-item label="死羔均重(kg)" prop="AvgDeadLambWeight">
          <el-input v-model.number="addForm.AvgDeadLambWeight" type="number" />
        </el-form-item>
        <el-form-item label="肥羊批次" prop="FatLambBatch">
          <el-input v-model="addForm.FatLambBatch" />
        </el-form-item>
        <el-form-item label="健羔数" prop="HealthyLambCount">
          <el-input v-model.number="addForm.HealthyLambCount" type="number" />
        </el-form-item>
        <el-form-item label="弱羔数" prop="WeakLambCount">
          <el-input v-model.number="addForm.WeakLambCount" type="number" />
        </el-form-item>
        <el-form-item label="畸形数" prop="DeformedLambCount">
          <el-input v-model.number="addForm.DeformedLambCount" type="number" />
        </el-form-item>
        <el-form-item label="死胎数" prop="StillbirthCount">
          <el-input v-model.number="addForm.StillbirthCount" type="number" />
        </el-form-item>
        <el-form-item label="畸胎数" prop="AbnormalFetusCount">
          <el-input v-model.number="addForm.AbnormalFetusCount" type="number" />
        </el-form-item>
        <el-form-item label="木乃伊数" prop="MummifiedFetusCount">
          <el-input v-model.number="addForm.MummifiedFetusCount" type="number" />
        </el-form-item>
        <el-form-item label="窝号" prop="LitterNumber">
          <el-input v-model="addForm.LitterNumber" />
        </el-form-item>
        <el-form-item label="性别" prop="Gender">
          <el-input v-model="addForm.Gender" />
        </el-form-item>
        <el-form-item label="当前栋舍" prop="CurrentPen">
          <el-input v-model="addForm.CurrentPen" />
        </el-form-item>
        <el-form-item label="当前栏位" prop="CurrentStall">
          <el-input v-model="addForm.CurrentStall" />
        </el-form-item>
        <el-form-item label="转入栋舍" prop="TransferInPen">
          <el-input v-model="addForm.TransferInPen" />
        </el-form-item>
        <el-form-item label="转入栏位" prop="TransferInStall">
          <el-input v-model="addForm.TransferInStall" />
        </el-form-item>
        <el-form-item label="转出栋舍" prop="TransferOutPen">
          <el-input v-model="addForm.TransferOutPen" />
        </el-form-item>
        <el-form-item label="负责人" prop="ResponsiblePerson">
          <el-input v-model="addForm.ResponsiblePerson" />
        </el-form-item>
        <el-form-item label="单据号" prop="DocumentNumber">
          <el-input v-model="addForm.DocumentNumber" />
        </el-form-item>
        <el-form-item label="状态" prop="Status">
          <el-input v-model="addForm.Status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getEweLambingList } from '../../utils/requestEweLambing'
import { addEweLambing } from '../../utils/requestEweLambing'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

function formatDate(dateStr: string) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  if (isNaN(d.getTime())) return ''
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}

const loading = ref(false)
const tableData = ref<any[]>([])
const searchForm = reactive({
  eweEarTag: '',
  transferInPen: '',
  transferOutPen: '',
  litterNumber: '',
  responsiblePerson: '',
  lambingDateStart: '',
  lambingDateEnd: ''
})
const dateRange = ref<string[]>([])
const searchFormRef = ref()
const router = useRouter()

function handleDateRangeChange(val: string[]) {
  if (val && val.length === 2) {
    searchForm.lambingDateStart = val[0]
    searchForm.lambingDateEnd = val[1]
  } else {
    searchForm.lambingDateStart = ''
    searchForm.lambingDateEnd = ''
  }
}

function mapFields(list: any[]) {
  return list.map(item => ({
    id: item.Id,
    eweEarTag: item.EweEarTag,
    lambingDate: item.LambingDate,
    gestationDays: item.GestationDays,
    lambingDifficulty: item.LambingDifficulty,
    maternalInstinct: item.MaternalInstinct,
    lactation: item.Lactation,
    mastitis: item.Mastitis,
    totalLambCount: item.TotalLambCount,
    totalLitterWeight: item.TotalLitterWeight,
    liveLambCount: item.LiveLambCount,
    liveLambWeight: item.LiveLambWeight,
    avgLiveLambWeight: item.AvgLiveLambWeight,
    deadLambCount: item.DeadLambCount,
    deadLambWeight: item.DeadLambWeight,
    avgDeadLambWeight: item.AvgDeadLambWeight,
    fatLambBatch: item.FatLambBatch,
    healthyLambCount: item.HealthyLambCount,
    weakLambCount: item.WeakLambCount,
    deformedLambCount: item.DeformedLambCount,
    stillbirthCount: item.StillbirthCount,
    abnormalFetusCount: item.AbnormalFetusCount,
    mummifiedFetusCount: item.MummifiedFetusCount,
    litterNumber: item.LitterNumber,
    gender: item.Gender,
    currentPen: item.CurrentPen,
    currentStall: item.CurrentStall,
    transferInPen: item.TransferInPen,
    transferInStall: item.TransferInStall,
    transferOutPen: item.TransferOutPen,
    responsiblePerson: item.ResponsiblePerson,
    creator: item.Creator,
    createTime: item.CreateTime,
    modifier: item.Modifier,
    modifyTime: item.ModifyTime,
    approver: item.Approver,
    approvalTime: item.ApprovalTime,
    documentNumber: item.DocumentNumber,
    status: item.Status
  }))
}

function handleSearch() {
  loading.value = true
  const params = {
    ...searchForm,
    lambingDateStart: dateRange.value[0] || undefined,
    lambingDateEnd: dateRange.value[1] || undefined
  }
  getEweLambingList(params)
    .then(res => {
      if (res.data && res.data.data) {
        tableData.value = mapFields(res.data.data)
      } else {
        tableData.value = []
      }
      loading.value = false
    }, () => {
      ElMessage.error('查询失败')
      loading.value = false
    })
}

function resetSearch() {
  Object.assign(searchForm, {
    eweEarTag: '',
    transferInPen: '',
    transferOutPen: '',
    litterNumber: '',
    responsiblePerson: '',
    lambingDateStart: '',
    lambingDateEnd: ''
  })
  dateRange.value = []
  handleSearch()
}

const showAddDialog = ref(false)
const addFormRef = ref()
const addForm = reactive({
  EweEarTag: '',
  LambingDate: '',
  GestationDays: '',
  LambingDifficulty: '',
  MaternalInstinct: '',
  Lactation: '',
  Mastitis: '',
  TotalLambCount: '',
  TotalLitterWeight: '',
  LiveLambCount: '',
  LiveLambWeight: '',
  AvgLiveLambWeight: '',
  DeadLambCount: '',
  DeadLambWeight: '',
  AvgDeadLambWeight: '',
  FatLambBatch: '',
  HealthyLambCount: '',
  WeakLambCount: '',
  DeformedLambCount: '',
  StillbirthCount: '',
  AbnormalFetusCount: '',
  MummifiedFetusCount: '',
  LitterNumber: '',
  Gender: '',
  CurrentPen: '',
  CurrentStall: '',
  TransferInPen: '',
  TransferInStall: '',
  TransferOutPen: '',
  ResponsiblePerson: '',
  DocumentNumber: '',
  Status: ''
})
const addRules = {
  EweEarTag: [{ required: true, message: '请输入种母耳号', trigger: 'blur' }],
  LambingDate: [{ required: true, message: '请选择分娩日期', trigger: 'change' }],
  GestationDays: [{ required: true, message: '请输入妊娠天数', trigger: 'blur' }],
  TotalLambCount: [{ required: true, message: '请输入羔总羔数', trigger: 'blur' }],
  // 可根据实际需求添加更多必填项
}

function submitAdd() {
  (addFormRef.value as any).validate((valid: boolean) => {
    if (!valid) return
    loading.value = true
    addEweLambing({ ...addForm })
      .then(res => {
        if (res.data && res.data.code === 200) {
          ElMessage.success('新增成功')
          showAddDialog.value = false
          handleSearch()
        } else {
          ElMessage.error(res.data?.msg || '新增失败')
        }
        loading.value = false
      }, () => {
        ElMessage.error('新增失败')
        loading.value = false
      })
  })
}

function goToAdd() {
  router.push('/EweLambing/add')
}

onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.container {
  padding: 20px;
}
.search-container {
  margin-bottom: 20px;
}
.table-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
